package com.zuo_book.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 配置静态资源映射
     * 将上传的文件目录映射到web访问路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            logger.info("创建上传目录: {} - 结果: {}", uploadDir.getAbsolutePath(), created);
        }
        
        // 配置资源路径
        String resourceLocation = "file:" + uploadDir.getAbsolutePath() + File.separator;
        logger.info("配置资源映射: /api/uploads/** -> {}", resourceLocation);
        
        // 配置静态资源映射，确保路径末尾有分隔符
        registry.addResourceHandler("/api/uploads/**")
                .addResourceLocations(resourceLocation);
                
        // 同时添加一个不带api前缀的映射，以防直接访问
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(resourceLocation);
    }
} 